import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import config from 'src/config/config';
import * as jwt from 'jsonwebtoken';

@Injectable()
export class UserService {
    constructor(@InjectModel('User') private readonly userModel) {}
    async find(where = {}, fields = null) {
        return await this.userModel.find(where, fields);
    }
    async create(userInfo) {
        return await this.userModel.create(userInfo);
    }
    async update(userInfo) {
        return await this.userModel.updateOne({ _id: userInfo._id }, userInfo);
    }
    async delete(userInfo) {
        return await this.userModel.deleteOne(userInfo);
    }
    async getUser(req) {
        const userInfoForSession = req.session.userInfo;
        if (userInfoForSession) {
            return userInfoForSession;
        }
        const authCookie = req.signedCookies[config.authCookieKey];
        if (authCookie) {
            const { _id } = jwt.verify(authCookie, config.jwtSecret) as any;
            const user = await this.find({ _id });
            if (!user.length) throw new BadRequestException('用户不存在');
            req.session.userInfo = user[0];
            return user[0];
        } else {
            return;
        }
    }
}
